<template>
  <div class="container">
    <el-row class="mb10">
      <el-col :span="16" align="left">
        <div class="flex">
          <el-input clearable v-model="searchParams.name" placeholder="活动名称" style="width: 120px; margin-right: 15px">
          </el-input>

          <div class="conUnitName">
            <el-cascader @change="changeUnit" popper-class="gy-cascader" :options="data.orgAllList"
              :props="data.popupTreeProps" v-model="searchParams.undertakeUnit" :show-all-levels="false"
              placeholder="请选择所属单位" clearable>
              <template #default="{ data }">
                <el-tooltip :disabled="data.name.length < 13" class="item" effect="dark" :content="data.name"
                  placement="bottom-start">
                  <span>{{ data.name }}</span>
                </el-tooltip>
              </template>
            </el-cascader>
          </div>


          <el-select clearable v-model="searchParams.className" placeholder="活动分类">
            <el-option :label="el.text" :value="el.value" :key="k" v-for="(el, k) in options.classnameList" />
          </el-select>
          <!-- <SelectOption :options="options.classnameList" :multiple="false" :placeholder="'活动分类'" @changeValue="classnameChange"></SelectOption> -->
          <el-select clearable v-model="searchParams.competitionClass" placeholder="大赛类别">
            <el-option :label="el.text" :value="el.value" :key="k" v-for="(el, k) in options.competitionclassList" />
          </el-select>

          <el-button @click="getListData" class="ordinary">搜索</el-button>
        </div>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="lock" @click="getUnlock()" v-limit="'KJSL:KJYJ:SCHDYJ:UNLOCK'">解锁</el-button>
        <el-button class="unlock" @click="getLock()" v-limit="'KJSL:KJYJ:SCHDYJ:LOCK'">
          锁定
        </el-button>

        <el-button class="ordinary" @click="getExport()" v-limit="'KJSL:KJYJ:SCHDYJ:EXPERT'">
          批量导出
        </el-button>
        <el-button type="danger" @click="handleDelete()" v-limit="'KJSL:KJYJ:SCHDYJ:DELETE'">批量删除</el-button>

        <el-button type="primary" @click="add" v-limit="'KJSL:KJYJ:SCHDYJ:ADD'">新增</el-button>
      </el-col>
    </el-row>
    <div>
      <TableDate :loading="data.isLoading" :tableArr="allTableData" :pagination="data.pagination"
        :columns="data.columns" @selectItem="getCurrentList" :total="data.pagination.total" @delectTable="delectIds"
        @currentChange="currentChange" @sizeChange="sizeChange">

        <template #status="{ row }">
          <span v-if="row.lockflag == 1" style="color: brown">已锁定</span>
          <span v-else>
            <span v-if="row.status == 0" style="color: #ffc783">待确认</span>
            <span v-if="row.status == 1" style="color: #4bc151">已确定</span>
            <span v-if="row.status == 2" style="color: #b5f1ff">正常</span>
          </span>
        </template>

        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'"
            :disabled="row.lockflag == 1" v-limit="'KJSL:KJYJ:SCHDYJ:EDIT'" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary" @click="handleDetail(row)">详情</el-button>
          <el-button v-if="row.status == '0'" size="small" type="primary" :key="row.id + 'qr'"
            v-limit="'KJSL:KJYJ:SCHDYJ:CONFIRM'" :disabled="row.lockflag == 1" @click="confirm(row)">确认</el-button>
        </template>
      </TableDate>
    </div>

    <!--新增、修改、确认弹框-->
    <el-dialog v-model="data.dialogVisible" width="900px" :show-close="false" :close-on-click-modal="false">

      <template #title>
        <div class="my-header" v-loading="data.detail_loading">
          <el-tabs v-model="data.tableId" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm"
                status-icon>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="活动名称" prop="name">
                      <el-input placeholder="请输入" v-model="ruleForm.name" style="width: 250px" maxlength="20"
                        show-word-limit />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="活动时间" prop="startTime">
                      <el-date-picker v-model="ruleForm.startTime" type="data" value-format="YYYY-MM-DD"
                        placeholder="选择日期" clearable style="width: 250px" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="活动分类" prop="classId">
                      <el-select v-model="ruleForm.classId" placeholder="请选择" style="width: 250px">
                        <el-option :label="el.text" :value="el.value" :key="k"
                          v-for="(el, k) in options.classnameList" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="承担单位" prop="undertakeUnitId">
                      <popup-tree-input :data="data.orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
        ? $t('message.org.top_menu')
        : ruleForm.undertakeUnit
        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue3" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12" v-if='ruleForm.classId == "1"'>
                    <el-form-item label="大赛类别" prop="competitionClassId">
                      <el-select v-model="ruleForm.competitionClassId" placeholder="请选择" style="width: 250px">
                        <el-option :label="el.text" :value="el.value" :key="k"
                          v-for="(el, k) in options.competitionclassList" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if='ruleForm.classId == "1"'>
                    <el-form-item label="考核类别" prop="awardLevelId">
                      <el-select v-model="ruleForm.awardLevelId" placeholder="请选择" style="width: 250px">
                        <el-option :label="el.text" :value="el.value" :key="k" v-for="(el, k) in options.awardList" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12" v-if='ruleForm.classId'>
                    <el-form-item label="考核类别" >
                      <span
                        v-if="ruleForm.classId == 1 && ruleForm.competitionClassId == 1 && Number(ruleForm.awardLevelId) <= 3">A</span>
                        <span
                        v-if="ruleForm.classId == 1 && ruleForm.competitionClassId == 1 && Number(ruleForm.awardLevelId) ==4">B</span>
                        <span
                        v-if="ruleForm.classId == 1 && ruleForm.competitionClassId == 2 && Number(ruleForm.awardLevelId) <=3">B</span>
                        <span
                        v-if="ruleForm.classId == 1 && ruleForm.competitionClassId == 3 && Number(ruleForm.awardLevelId) <=3">B</span>
                        <span
                        v-if="ruleForm.classId == 1 && ruleForm.competitionClassId == 4 && Number(ruleForm.awardLevelId) <=3">B</span>

                        <span
                        v-if="ruleForm.classId == 2" >B</span>
                        
                        <span
                        v-if="ruleForm.classId == 3" >C</span>

                        <span
                        v-if="ruleForm.classId == 1  && ruleForm.competitionClassId == 2 && Number(ruleForm.awardLevelId) == 4" >C</span>

                        <span
                        v-if="ruleForm.classId == 1  && ruleForm.competitionClassId == 3 && Number(ruleForm.awardLevelId) == 4" >C</span>

                        <span
                        v-if="ruleForm.classId == 1  && ruleForm.competitionClassId == 4 && Number(ruleForm.awardLevelId) == 4" >C</span>

                        <span
                        v-if="ruleForm.classId == 5 " >C</span>

                        <span
                        v-if="ruleForm.classId ==4 " >D</span>

                        <span
                        v-if="ruleForm.classId == 6 " >D</span>

                    </el-form-item>
                  </el-col>

                </el-row>
                <!--                <el-form-item label="参与人员" @click="choosePersion" prop="joinPersons" style="width:93%">-->

                <!--                  <user-list-modal v-model="ruleForm.joinPersons" @update:modelValue="changeValue2" :default-users="[]"
                    :multiple="true" :devType="'platform'"  />-->
                <el-form-item label="参与人员" prop="joinPersons" style="width: 93%">
                  <user-list-modal v-model="ruleForm.joinPersons" :selectIds="ruleForm.joinPersonIds"
                    @changePartake="handleProjectLeader" onlyKey="partake" :default-users="selectArr" :multiple="true"
                    :devType="'platform'" />
                </el-form-item>
                <el-form-item label="活动说明" prop="activityDescription">
                  <el-input :style="{ width: '680px' }" v-model="ruleForm.activityDescription"
                    :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" maxlength="50"
                    show-word-limit />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input :style="{ width: '680px' }" v-model="ruleForm.remark" :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea" placeholder="请输入" maxlength="50" show-word-limit />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="2">
              <platformFiles :files="data.files" @filesParams="filesParams" download="KJSL:KJYJ:SCHDYJ:DOWNLOAD"
                upload="KJSL:KJYJ:SCHDYJ:UPLOAD" fileDelete="KJSL:KJYJ:SCHDYJ:FILEDELETE"></platformFiles>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="3" v-if="data.currentHandle == '2'">
              <record :changeLogs="data.changeLogs"></record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button type="primary" @click="submitForm()">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="data.detailVisible" width="900px" :show-close="false" :close-on-click-modal="false">

      <template #title>
        <div class="my-header" v-loading="data.detailVisible_loading">
          <el-tabs v-model="data.tableId" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm"
                status-icon>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="活动名称" prop="name">
                      <el-input placeholder="请输入" v-model="ruleForm.name" style="width: 250px" :disabled="1" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="活动时间" prop="startTime">
                      <el-date-picker v-model="ruleForm.startTime" type="data" value-format="YYYY-MM-DD"
                        placeholder="选择日期" clearable style="width: 250px" :disabled="1" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="活动分类" prop="classId">
                      <el-select v-model="ruleForm.classId" placeholder="请选择" style="width: 250px" :disabled="1">
                        <el-option :label="el.text" :value="el.value" :key="k"
                          v-for="(el, k) in options.classnameList" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if='ruleForm.classId == "1"'>
                    <el-form-item label="大赛类别" prop="competitionClassId">
                      <el-select v-model="ruleForm.competitionClassId" placeholder="请选择" style="width: 250px"
                        :disabled="1">
                        <el-option :label="el.text" :value="el.value" :key="k"
                          v-for="(el, k) in options.competitionclassList" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12" v-if='ruleForm.classId == "1"'>
                    <el-form-item label="获奖等级" prop="awardLevelId">
                      <el-select v-model="ruleForm.awardLevelId" placeholder="请选择" style="width: 250px" :disabled="1">
                        <el-option :label="el.text" :value="el.value" :key="k" v-for="(el, k) in options.awardList" />
                      </el-select>
                    </el-form-item>

                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="承担单位" prop="undertakeUnitId">
                      <popup-tree-input :data="data.orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
        ? $t('message.org.top_menu')
        : ruleForm.undertakeUnit
        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue3" :disabled="1" />
                    </el-form-item>

                  </el-col>
                </el-row>
                <el-form-item label="参与人员" @click="choosePersion" prop="joinPersonIds">
                  <user-list-modal v-model="ruleForm.joinPersons" @update:modelValue="changeValue2" :default-users="[]"
                    :multiple="false" :devType="'platform'" :disabled="1" />
                </el-form-item>
                <el-form-item label="活动说明" prop="activityDescription">
                  <el-input :style="{ width: '680px' }" v-model="ruleForm.activityDescription"
                    :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" :disabled="1" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input :style="{ width: '680px' }" v-model="ruleForm.remark" :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea" placeholder="请输入" :disabled="1" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="2">
              <platformFilesxq :files="data.files" @filesParams="filesParams" download="KJSL:KJYJ:SCHDYJ:DOWNLOAD"
                upload="KJSL:KJYJ:SCHDYJ:UPLOAD" fileDelete="KJSL:KJYJ:SCHDYJ:FILEDELETE"></platformFilesxq>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="3" v-if="data.currentHandle == '2'">
              <record :changeLogs="data.changeLogs"></record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="data.addPerson" append-to-body width="60%" top="10vh" :show-close="false"
      :close-on-click-modal="false">

      <template #title>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="员工列表" name="first">
            <div>
              <el-row>
                <el-col :span="24" align="right">
                  <el-input v-model="data.params.name" placeholder="姓名" style="width: 150px; margin-right: 15px" />
                  <SelectOption :options="data.orgAllList" style="width: 200px; margin-right: 15px"
                    :placeholder="'归属单位'" @change-value="changeValueUnit">
                  </SelectOption>
                  <el-button class="ordinary">搜索</el-button>

                  <Table :tableArr="data.userList" @selectItem="selectItemFn" :columns="data.tableHeader"
                    :pagination="data.page" :operate="true" :isCheckbox="false" :total="data.page.total"></Table>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closePersonbox">关闭</el-button>
          <el-button type="primary" @click="save()">选择</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import platformFiles from "@/views/science/components/platformFiles/platformFiles.vue";
import platformFilesxq from "@/views/science/components/platformFiles/platformFilesxq.vue";
import record from "@/views/science/components/record/record.vue";
import TableDate from "@/views/science/components/table/TableDate.vue";
import moment from "moment";
import { ObjectType } from "typings/interfaces";
import { onMounted, reactive, ref } from "vue";
// getOrgInfo,
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import UserListModal from "@/views/project/components/UserListModal/index.vue";
import PopupTreeInput from "@/views/science/components/PopupTreeInput/index.vue";
import Table from "@/views/science/components/table/table.vue";
import SelectOption from "@/views/science/technologyStrength/components/selectOption/index.vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { Modals, tips } from "../../components/tips/tips";

import {
  deleteList,
  getConfirm,
  getDelect,
  getDetailById,
  getInnovativeTalentTeamLock,
  getInnovativeTalentTeamUnlock,
  getJoinPersons,
  getTeam,
  getTotalList,
  insert,
  monthReportUpdate,
  selectItemOpen,
  updata,
} from "../api/double";
import Api from "../api/profess";
import tableHead from "./tableHeader.json";

export default {
  components: {
    Table,
    TableDate,
    SelectOption,
    platformFiles,
    platformFilesxq,

    record,
    UserListModal,
    PopupTreeInput,
  },
  setup() {
    const deptForm = {
      parentId: 0,
      parentName: "",
    };

    onMounted(() => {
      getOrgList();

      yonghu();
    });
    const store = useStore();
    const budgetYear = ref("2023");
    const activeName = ref("first");
    const choosePersion = () => {
      // 选择参与人员按钮事件
      data.persionDialogVisible = true;
      getJoinList();
    };
    let data = reactive({
      popupTreeProps: {
        label: "name",
        children: "children",
        value: "id",
        checkStrictly: true,
      },
      tableId: "1",
      isLoading: false,
      detail_loading: false,
      columns: tableHead.doubleHeader,
      pagination: { page: 1, limit: 10, total: 0 }, //分页
      dialogVisible: false, //  新增修改确认项目弹框
      persionDialogVisible: false, //  选择参与人员弹框
      reDate: "",
      files: [],
      changeLogs: [],
      userList: [],
      joinPersonIds: [],
      joinPersons: [],
      addPerson: false,
      list: [],
      params: {
        current: 1,
        size: 10,
        name: "",
        unitOrg: "",
        undertakeUnit: "",
        className: "",
        competitionClass: "",
      },
      ids: [],
      page: { page: 1, limit: 10, total: 0 },
      tableHeader: [
        {
          key: "name",
          type: "name",
          width: 140,
          label: "活动名称",
        },
        {
          key: "units",
          type: "undertakeUnit",
          width: 140,
          label: "承担单位",
        },
        {
          key: "estimated",
          type: "joinMethod",
          width: 140,
          label: "参与方式",
        },
        {
          key: "actual",
          type: "className",
          width: 140,
          label: "活动分类",
        },
        {
          key: "annual",
          type: "competitionClass",
          width: 140,
          label: "大赛类别",
        },
        {
          key: "annual",
          type: "awardLevel",
          width: 140,
          label: "获奖等级",
        },
        {
          key: "annual",
          type: "joinTime",
          width: 140,
          label: "参加时间",
        },
        {
          key: "annual",
          type: "remark",
          width: 140,
          label: "状态",
        },
      ],
      currentHandle: "",
      allTableData: [],
      orgAllList: [],
      detailVisible_loading: false,
      detailVisible: false,
      selectedRows: [] as any,
    });

    const handleDetail = (row) => {
      for (let key in ruleForm) {
        for (let key2 in row) {
          if (key === key2) {
            ruleForm[key] = row[key2];
          }
        }
      }

      detailVisibleData(row.id);
      data.detailVisible = true;
      data.currentHandle = "2";
    };

    //详情数据获取
    const detailVisibleData = async (id) => {
      data.detailVisible_loading = true;
      let res = await getDetailById({ id });

      // 附近和变更记录
      if (res.data.data.list) {
        data.files = res.data.data.list;
      }
      if (res.data.data.changeLogs) {
        data.changeLogs = res.data.data.changeLogs;
      }
      data.detailVisible_loading = false;
    };

    const handleClose = () => {
      data.detailVisible = false;
      data.tableId = "1";
    };

    let selectedRows: ObjectType[] = [];
    let columns = [
      {
        key: "name",
        type: "name",
        width: 140,
        label: "活动名称",
      },
      {
        key: "units",
        type: "undertakeUnit",
        width: 140,
        label: "承担单位",
      },
      {
        key: "estimated",
        type: "joinMethod",
        width: 140,
        label: "参与方式",
      },
      {
        key: "actual",
        type: "className",
        width: 140,
        label: "活动分类",
      },
      {
        key: "annual",
        type: "competitionClass",
        width: 140,
        label: "大赛类别",
      },
      {
        key: "annual",
        type: "awardLevel",
        width: 140,
        label: "获奖等级",
      },
      {
        key: "annual",
        type: "joinTime",
        width: 140,
        label: "参加时间",
      },
      {
        key: "annual",
        type: "remark",
        width: 140,
        label: "状态",
      },
    ];
    const ruleForm = reactive({
      id: "",
      name: "", // 活动名称
      startTime: "", // 活动时间
      classId: "",
      className: "", // 活动分类
      competitionClassId: "",
      competitionClass: "", //大赛类别
      undertakeUnitId: "",
      undertakeUnit: "", // 承担单位
      awardLevelId: "",
      awardLevel: "", // 获奖等级
      joinPersonIds: [], // 参与人员ID
      joinPersons: [], // 参与人员ID
      activityDescription: "", // 活动说明
      examineCategory:'',
      remark: "", // 备注
      list: [],
    }) as any;

    let filesParams = (params) => {
      data.files = params;
    };

    let changeUnit = (val) => {
      if (val == null) {
        searchParams.undertakeUnit = "";
        return false;
      }
      if (val.length > 0) {
        let unitId = val[val.length - 1];
        searchParams.undertakeUnit = unitId;
      }
    };

    let getOrgList = () => {
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then((res) => {
        data.orgAllList = res.data.data;
      });
    };

    let loading = ref(true);
    // 列表
    let allTableData = ref([]);
    let page = reactive({
      page: 1,
      pageSize: 10,
      total: 0,
    });
    // 查询参数
    const searchParams = reactive({
      name: "",
      undertakeUnit: "",
      className: "",
      competitionClass: "",
    });
    interface Config {
      id: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };

    let handleConfirm = (row) => {
      data.dialogVisible = true;
    };
    //页码回调
    const currentChange = (pageNum) => {
      page.page = pageNum;
      getListData();
    };
    //条数回调
    const sizeChange = (pageSize) => {
      page.page = 1;
      page.pageSize = pageSize;
      getListData();
    };

    let getListData = () => {
      data.isLoading = true;
      getTotalList({
        page: page.page,
        pageSize: page.pageSize,
        ...searchParams,
      })
        .then((res) => {
          let resData = res.data.data.records;

          resData.map((item) => {
            item.startTime = moment(item.startTime).format("YYYY-MM-DD");
          });

          allTableData.value = resData;

          data.pagination.total = res.data.data.total;
          data.isLoading = false;
        })
        .finally(() => {
          loading.value = false;
        });
    };
    getListData();

    // 参与人员列表
    let allJoinList = ref([]);
    let searchJoin = reactive({
      name: "", //名称
      unitOrg: "", //机构ID
    });
    let pageJoin = {
      page: 1,
      pageSize: 10,
      total: 0,
    };
    const getJoinList = () => {
      getJoinPersons({
        current: pageJoin.page,
        size: pageJoin.pageSize,
        ...searchJoin,
      }).then((res) => {
        console.log("参与人员列表de", res);

        data.userList = res.data.data.records;
        data.page.total = res.data.data.total;
      });
      // .finally(() => {})
    };

    // 参与人员相关声明数据
    const callPerson: any = ref([]);

    const person: any = ref([]);

    const selectItemFn = (item) => {
      item.filter((item, index) => {
        const obj = {
          username: item.username,
          userId: item.userId,
        };
        if (JSON.stringify(person.value).indexOf(JSON.stringify(obj)) == -1)
          person.value.push(obj);
      });
    };

    const addPersonBox = () => {
      data.userList = [];
      getListData();
      data.addPerson = true;
    };

    const handleClosePerson = (tag) => {
      callPerson.value.splice(callPerson.value.indexOf(tag), 1);
      handleSelectPerson(callPerson);
    };

    const closePersonbox = () => {
      data.addPerson = false;
      person.value = [];
    };

    const save = () => {
      data.addPerson = false;
      person.value.filter((item, index) => {
        //console.log(JSON.stringify(callPerson.value).indexOf(JSON.stringify(item)))
        if (JSON.stringify(callPerson.value).indexOf(JSON.stringify(item)) == -1)
          callPerson.value.push(item);
      });
      person.value = [];
      handleSelectPerson(callPerson);
    };

    const changeValueUnit = (item) => {
      data.params.unitOrg = item.id;
    };
    const getCurrentList = (currentList) => {
      console.log(currentList, "getCurrentList");
      data.selectedRows = currentList;
    };
    const delectIds = (ids) => {
      data.ids = ids;
    };

    const arrname: any = reactive([]); //选中的人员name合集
    const arrid: any = reactive([]); //选中的人员id合集
    const handleSelectPerson = (val) => {
      val.value.map((item) => {
        if (arrname.indexOf(item.username) == -1) arrname.push(item.username);
        if (arrid.indexOf(item.userId) == -1) arrid.push(item.userId);
      });
    };

    const selectIds = (a) => {
      data.ids = a;
    };

    let close = () => {
      data.dialogVisible = false;
      data.tableId = "1";
    };

    // 存储下拉框数组的对象
    const options: any = reactive({
      classnameList: [],
      competitionclassList: [],
      belongingunitList: [],
      awardList: [],
      yhrenList: [],
    });
    //用户单位
    const yonghu = () => {
      request({
        url: "/checc-api/user/getAll",
        method: "get",
      }).then((res) => {
        console.log("587用户单位:{}", res.data.data);
        options.yhrenList = res.data.data;
      });
    };

    const start = () => {
      // 活动分类
      Api.getDictByCode({ code: "KJSL_ACTIVITY_CLASSIFICATION" }).then((res) => {
        debugger;
        options.classnameList = res.data.data;
      });
      // 获奖等级
      Api.getDictByCode({ code: "KJSL_AWARD_LEVEL" }).then((res) => {
        options.awardList = res.data.data;
      });
      // 大赛类别
      Api.getDictByCode({ code: "KJSL_COMPETITION_CATEGORY" }).then((res) => {
        options.competitionclassList = res.data.data;
      });

      // 承担单位
      // getOrgsByLoginUser().then((res) => {
      //   options.belongingunitList = res.data.data
      // })
    };
    start();

    // 批量删除

    const handleDelete = async () => {
      if (data.ids.length) {
        Modals("是否删除选择内容", "提示", "warning")
          .then(async () => {
            let res = await getDelect(data.ids);
            if (res.data.success) {
              tips("删除成功", "success");
              getListData();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else {
        tips("请选择", "warning");
      }
    };

    getListData();

    let getDetail = async (id) => {
      data.detail_loading = true;
      let res = await getDetailById({ id });
      //res.data.data.joinPersons = res.data.data.joinPersons.split(',')
      //res.data.data.joinPersonIds = res.data.data.joinPersonIds.split(',')
      ruleForm.joinPersonIds = res.data.data.joinPersonIds.split(",");
      ruleForm.joinPersons = res.data.data.joinPersons.split(",");
      console.log(1111, res.data.data.joinPersons, res.data.data.joinPersonIds);
      // 附近和变更记录
      if (res.data.data.list) {
        data.files = res.data.data.list;
      }
      if (res.data.data.changeLogs) {
        data.changeLogs = res.data.data.changeLogs;
      }
      data.detail_loading = false;
    };

    //  编辑
    const handleEdit = (row) => {
      for (let key in ruleForm) {
        for (let key2 in row) {
          if (key === key2) {
            ruleForm[key] = row[key2];
          }
        }
      }

      getDetail(row.id);
      data.dialogVisible = true;
      data.currentHandle = "2";
    };

    // 新增
    const rules = reactive({
      name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      startTime: [{ required: true, message: "请选择活动时间", trigger: "change" }],
      classId: [{ required: true, message: "请选择活动分类", trigger: "change" }],
      competitionClassId: [
        { required: true, message: "请选择大赛类别", trigger: "change" },
      ],
      undertakeUnitId: [{ required: true, message: "请选择承担单位", trigger: "change" }],
      awardLevelId: [{ required: true, message: "请选择获奖等级", trigger: "change" }],
      // joinPersonIds: [{ required: true, message: '请选择参与人员', trigger: 'change' }],
      joinPersonIds: [{ required: true, message: "请选择参与人员", trigger: "change" }],
      joinPersons: [{ required: true, message: "请选择参与人员", trigger: "blur" }],
      activityDescription: [
        { required: true, message: "请输入活动说明", trigger: "blur" },
      ],
      username: [{ required: true, message: "请选择参与人员", trigger: "change" }],
    });

    const add = () => {
      for (let key in ruleForm) {
        ruleForm[key] = "";
      }
      console.log("ruleForm", ruleForm);
      data.files = [];

      data.dialogVisible = true;
      data.currentHandle = "1";
    };
    const ruleFormRef = ref();
    // 保存
    const submitForm = async () => {
      await ruleFormRef.value.validate(async (valid, fields) => {
        if (!valid) {
          return tips("请将基本信息补充完整", "warning");
        }
        // 活动分类
        let obj = options.classnameList.filter((item) => {
          return item.value === ruleForm.classId;
        });
        // 获奖等级
        let obj2 = options.awardList.filter((item) => {
          return item.value === ruleForm.awardLevelId;
        });
        // 大赛类别
        let obj3 = options.competitionclassList.filter((item) => {
          return item.value === ruleForm.competitionClassId;
        });
        // 承担单位
        // let obj4 = options.belongingunitList.filter((item) => {
        //   return item.id === ruleForm.undertakeUnitId
        // })
        // 参与人员
        // let obj5 = options.yhrenList.filter((item) => {
        //   return item.userId === ruleForm.joinPersonIds
        // })
        if(ruleForm.awardLevelId){
          ruleForm.awardLevel = obj2[0].text;
        }

        if(ruleForm.classId){
          ruleForm.className = obj[0].text;
        }


        if(ruleForm.competitionClassId){
          ruleForm.competitionClass = obj3[0].text;
        }


     
 

        // ruleForm.undertakeUnit = obj4[0] ? obj4[0].name : ''
        // ruleForm.joinPersons = obj5[0].username
        ruleForm.list = data.files;
        ruleForm.joinPersonIds = ruleForm.joinPersonIds.join(",");
        ruleForm.joinPersons = ruleForm.joinPersons.join(",");
    

        if (data.currentHandle == "1") {
          const rs = await insert(ruleForm);

          if (rs.data.code == 200) {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            data.dialogVisible = false;
            getListData();
          }
        } else if (data.currentHandle == "2") {
          const rs = await updata(ruleForm);

          if (rs.data.code == 200) {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            data.dialogVisible = false;
            getListData();
          }
        }
      });
    };
    // 月度账单
    let monthVisible = reactive({ isShow: false });
    let openTableData = ref([]);
    let cur = { belongingUnit: "", budgetYear: "" };
    const getOpenData = () => {
      selectItemOpen({
        belongingUnit: cur.belongingUnit,
        budgetYear: cur.budgetYear,
      }).then((res) => {
        openTableData.value = res.data.data;
      });
    };
    const openMonthTable = (row) => {
      cur = row;
      monthVisible.isShow = true;
      getOpenData();
    };

    const handleEditItem = (row) => {
      console.log(row);

      row.isEdit = true;
    };
    const cancelItem = (row) => {
      row.isEdit = false;
    };
    const saveItem = (row) => {
      monthReportUpdate({
        belongingUnit: row.belongingUnit,
        dataBasedMonth: row.dataBasedMonth,
        actualAmount: row.actualAmount,
        id: row.id,
      }).then(() => {
        getOpenData();
        ElMessage({
          message: "操作成功",
          type: "success",
        });
      });
    };

    // 确定当前流程
    let confirm = async (row) => {
      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await getConfirm(row.id);
          if (res.data.success) {
            getListData();
          }
        })
        .catch(() => { });
    };

    const getLock = async () => {
      if (data.ids.length == 1) {
        let flag = true;
        console.log(data.selectedRows, "selectedRows");
        data.selectedRows.forEach((obj) => {
          if (obj.status == "0") {
            flag = false;
          }
        });
        if (!flag) {
          ElMessage({
            message: "请确认后再进行锁定",
            type: "warning",
          });
          return;
        }
        Modals("是否锁定选择内容", "提示", "warning")
          .then(async () => {
            let res = await getInnovativeTalentTeamLock(data.ids);
            if (res.data.success) {
              tips("锁定成功", "success");
              getListData();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("锁定功能不可批量操作", "warning");
      }
    };
    const getUnlock = async () => {
      if (data.ids.length == 1) {
        Modals("是否解锁选择内容", "提示", "warning")
          .then(async () => {
            let res = await getInnovativeTalentTeamUnlock(data.ids);
            if (res.data.success) {
              tips("解锁成功", "success");
              getListData();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("解锁功能不可批量操作", "warning");
      }
    };

    const getExport = async () => {
      let msg = "是否导出全部数据";
      if (data.ids.length > 0) {
        msg = "是否导出所选数据";
      }
      Modals(msg, "提示", "warning")
        .then(async () => {
          const params = {
            ...searchParams,
            // ...data.params,
            ids: data.ids,
          };
          let res = await getTeam(params);
          console.log(res, "getTeam");
        })
        .catch(() => {
          console.log("点击了取消");
        });
    };

    //选择人员的回调
    const handleProjectLeader = (ids: string[] = [], names: string[] = []) => {
      ruleForm.joinPersonIds = ids.reduce(
        (now, next) => (now.includes(next) ? now : now.concat(next)),
        ruleForm.joinPersonIds || []
      );
      ruleForm.joinPersons = names.reduce(
        (now, next) => (now.includes(next) ? now : now.concat(next)),
        ruleForm.joinPersons || []
      );
    };

    //联系人
    const changeValue2 = (item) => {
      ruleForm.joinPersons = item.cname;
      ruleForm.joinPersonIds = item.userId;
    };
    const changeValue3 = (item) => {
      ruleForm.undertakeUnit = item.name;
      ruleForm.undertakeUnitId = item.id;
    };

    return {
      activeName,
      currentChange,
      sizeChange,
      handleDelete,
      changeValue2,
      changeValue3,
      selectIds,
      filesParams,
      choosePersion,
      ruleFormRef,
      budgetYear,
      options,
      data,
      allTableData,
      page,
      selectedRows,
      columns,
      searchParams,
      handleEdit,
      close,
      // 列表
      getListData,
      //参与人员列表
      getJoinList,
      allJoinList,
      searchJoin,
      pageJoin,
      handleSelectionChange,
      // 新增
      add,
      submitForm,
      ruleForm,
      rules,
      deleteList,
      getLock,
      handleConfirm,
      getUnlock,
      getExport,

      selectArr,

      monthVisible,
      openMonthTable,
      openTableData,
      handleEditItem,
      cancelItem,
      saveItem,
      getDetail,
      confirm,
      changeUnit,

      callPerson,
      selectItemFn,
      addPersonBox,
      handleClosePerson,
      closePersonbox,
      save,
      changeValueUnit,
      getCurrentList,
      delectIds,
      deptForm,
      handleDetail, //详情
      handleClose, //详情
      handleProjectLeader,
    };
  },
};
</script>

<style lang="scss">
.conUnitName {
  display: inline-block;
  width: 200px;
}

.gy-cascader {
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>

<style lang="scss" scoped>
.box_s {
  overflow-x: auto;
}

.el-table__body-wrapper {
  overflow-x: auto !important;
}

.el_table_box {
  overflow-x: auto !important;
  scrollbar-width: none;
  overflow-x: auto;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  height: 100%;
  // line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
  vertical-align: middle;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.container {
  background-color: white;
  padding: 20px;
}

.el-col {
  line-height: 40px;
}

.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/.el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.mb10 {
  margin-bottom: 10px;
}

.tc {
  text-align: center;
}
</style>
